package com.yao.presenter;

import android.util.Base64;
import com.alibaba.fastjson.JSON;
import com.base.mvp.BasePresenter;
import com.yao.AppConfig;
import com.yao.http.Http;
import com.yao.http.Result;
import com.yao.presenter.bean.UserBean;
import com.yao.util.PreferenceCache;
import com.yao.util.UserUtil;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

import java.util.HashMap;

public class UserPresenter extends BasePresenter<UserContract.View, UserContract.Model> implements UserContract.Presenter {

    @Override
    protected UserContract.Model getModel() {
        return new UserModel();
    }

    @Override
    public void login(String un, String psd) {
        if (isViewAttached()) {
            mView.showLoading();
            Flowable<Result<UserBean>> flowable = mModel.login(un, psd);
            try {
                mDisposable = flowable.subscribe(new Consumer<Result<UserBean>>() {
                    @Override
                    public void accept(Result<UserBean> result) {
                        mView.hideLoading();
                        if (result.getCode() == 1) {
                            UserBean userBean = result.getData();
                            PreferenceCache.putUserInfo(JSON.toJSONString(userBean));
                            PreferenceCache.putUserName(un);
                            PreferenceCache.putToken(userBean.getToken());
                            mView.onSuccess();
                        } else {
                            mView.onFail(result.getCode(), result.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                        mView.hideLoading();
                        mView.onFail(0, throwable.getMessage());
                    }
                });
            } catch (RuntimeException e) {
                mView.hideLoading();
                mView.onError(e);
            }
        }
    }

    class UserModel implements UserContract.Model {
        @Override
        public Flowable<Result<UserBean>> login(String un, String psd) {
            String privateKey = UserUtil.getPrivateToken();
            HashMap<String, String> paramsMap = new HashMap<>();
            try {
                byte[] bUn = UserUtil.encryptByPublicKey(un.getBytes(), Base64.decode(privateKey, Base64.NO_PADDING));
                byte[] bPsd = UserUtil.encryptByPublicKey(psd.getBytes(), Base64.decode(privateKey, Base64.NO_PADDING));
                paramsMap.put("username", Base64.encodeToString(bUn, Base64.NO_PADDING));
                paramsMap.put("password", Base64.encodeToString(bPsd, Base64.NO_PADDING));
            } catch (Exception e) {
                e.printStackTrace();
            }
            RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), JSON.toJSONString(paramsMap));
            return getHttp().login(body).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread());
        }

        @Override
        public UserContract.Api getHttp() {
            return Http.getInstance().getRetrofit().create(UserContract.Api.class);
        }

        @Override
        public void destroy() {
            Http.cancleAll(AppConfig.Http.API_LOGIN);
        }
    }
}
